package com.softserveinc.cheatsheet.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.softserveinc.cheatsheet.entity.UserAccount;
import com.softserveinc.cheatsheet.services.UserService;

@Controller
public class RegistrationFormController  {
	
	@Autowired
	UserService service;
	
	 @RequestMapping(value = "/registrationForm.htm", method = RequestMethod.GET)
	 public void registrationForm(Model model) {
		 model.addAttribute("user",new UserAccount());
	 }
	
	 @RequestMapping(value = "/registration.htm", method = RequestMethod.POST)
	 public ModelAndView registerUser(@ModelAttribute UserAccount user, Model model) {
		model.addAttribute("user", user);
		
		user = service.saveUser(user);
		
		Authentication authentification = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
		SecurityContextHolder.getContext().setAuthentication(authentification);
		
		return new ModelAndView("registrationResult","user", user);
	 }

}
